package com.juxing.service.imCenter.impl;

import io.rong.ApiHttpClient;
import io.rong.models.FormatType;
import io.rong.models.SdkHttpResult;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.juxing.sdk.util.StringUtil;
import com.juxing.service.imCenter.IImCenterService;
import com.juxing.service.imCenter.bean.UserRcTokenBean;
import com.juxing.service.imCenter.cache.IUserRcTokenCache;
import com.juxing.service.imCenter.dao.IUserRcTokenDao;

public class ImCenterServiceImpl implements IImCenterService, InitializingBean {
	
	private static final Logger logger = LoggerFactory.getLogger(ImCenterServiceImpl.class);
	
	@Autowired
	private IUserRcTokenDao userRcTokenDao;
	@Autowired
	private IUserRcTokenCache userRcTokenCache;
	
	private String rongCloudAppKey;
	private String rongCloudAppSecret;
	
	@Override
	public UserRcTokenBean getUserRcToken(int userId) {
		UserRcTokenBean bean = userRcTokenCache.getUserRcTokenBean(userId);
		if(bean == null) {
			bean = userRcTokenDao.queryByUserId(userId);
		}
		if(bean != null) {
			if(bean.getExpireAt() > 0 && System.currentTimeMillis() > bean.getExpireAt()) {//如果已经过期了
				return null;
			}
		}
		return bean;
	}
	
	@Override
	public UserRcTokenBean refreshUserRcToken(int userId, String name, String portraitUri) {
		
		String token = null;
		int retry = 3;
		while(retry-- > 0) {
			try {
				SdkHttpResult result = ApiHttpClient.getToken(rongCloudAppKey, rongCloudAppSecret, "" + userId, name, portraitUri, FormatType.json);
				logger.debug("{}", result);
				if(result.getHttpCode() == 200) {
					JSONObject retJson = JSON.parseObject(result.getResult());
					if(retJson.getInteger("code") == 200) {
						token = retJson.getString("token");
						break;
					} else {
						logger.warn("warn.{}", result);
					}
				} else {
					logger.warn("warn.{}", result);
				}
			} catch (Exception e) {
				logger.warn("error", e);
			}			
		}
		if(StringUtil.isNotEmpty(token)) {
			UserRcTokenBean bean = new UserRcTokenBean();
			bean.setUserId(userId);
			bean.setToken(token);
			bean.setExpireAt(0);//暂时永久有效
			
			userRcTokenDao.insert(bean);
			userRcTokenCache.setUserRcTokenBean(bean);
			return bean;
		}
		return null;
	}
	
	public String getRongCloudAppKey() {
		return rongCloudAppKey;
	}
	public void setRongCloudAppKey(String rongCloudAppKey) {
		this.rongCloudAppKey = rongCloudAppKey;
	}
	public String getRongCloudAppSecret() {
		return rongCloudAppSecret;
	}
	public void setRongCloudAppSecret(String rongCloudAppSecret) {
		this.rongCloudAppSecret = rongCloudAppSecret;
	}
	@Override
	public void afterPropertiesSet() throws Exception {
		logger.error("rongcloud appKey={}, appSecret={}", rongCloudAppKey, rongCloudAppSecret);
		if(StringUtil.isEmpty(rongCloudAppKey) || StringUtil.isEmpty(rongCloudAppSecret)) {
			throw new RuntimeException("rongCloudAppKey or rongCloudAppSecret can not be empty.");
		}
	}
}
